import 'dart:async';
import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'native_video_cache_manager.dart';

/// 缓存内存管理器
/// 管理缓存监听器的内存使用，实现LRU缓存策略防止内存泄漏
class CacheMemoryManager {
  static CacheMemoryManager? _instance;
  static CacheMemoryManager get instance =>
      _instance ??= CacheMemoryManager._();

  CacheMemoryManager._();

  // 内存管理配置
  int maxActiveListeners = 50;
  int maxCacheStates = 100;
  static const Duration cleanupInterval = Duration(minutes: 2);
  static const Duration staleStateTimeout = Duration(minutes: 10);

  // 监听器管理
  final Map<String, Set<CacheProgressListener>> _progressListeners = {};
  final Map<String, Set<CacheStatusListener>> _statusListeners = {};
  final Map<String, Set<CacheErrorListener>> _errorListeners = {};

  // 缓存状态管理（LRU策略）
  final LinkedHashMap<String, String> _cacheStates = LinkedHashMap();
  final Map<String, DateTime> _stateTimestamps = {};

  Timer? _cleanupTimer;
  bool _isInitialized = false;

  /// 初始化内存管理器
  void initialize({int? maxUrls, int? maxMemoryUsage}) {
    if (_isInitialized) return;

    // 如果提供了参数，更新默认值
    if (maxUrls != null) {
      maxCacheStates = maxUrls;
    }
    if (maxMemoryUsage != null) {
      // 根据内存使用量调整最大监听器数量（简单估算）
      maxActiveListeners = (maxMemoryUsage / 1024).round();
    }

    _startCleanupTimer();
    _isInitialized = true;
    debugPrint(
        'CacheMemoryManager: 初始化完成 - maxUrls: $maxCacheStates, maxMemoryUsage: ${maxMemoryUsage ?? "默认"}');
  }

  /// 添加进度监听器（带内存控制）
  void addProgressListener(String url, CacheProgressListener listener) {
    _checkMemoryPressure();

    _progressListeners.putIfAbsent(url, () => <CacheProgressListener>{});
    _progressListeners[url]!.add(listener);

    debugPrint(
        'CacheMemoryManager: 添加进度监听器 - $url (总监听器: ${_getTotalListenerCount()})');
  }

  /// 移除进度监听器
  void removeProgressListener(String url, CacheProgressListener listener) {
    final listeners = _progressListeners[url];
    if (listeners != null) {
      listeners.remove(listener);
      if (listeners.isEmpty) {
        _progressListeners.remove(url);
      }
    }

    debugPrint(
        'CacheMemoryManager: 移除进度监听器 - $url (剩余监听器: ${_getTotalListenerCount()})');
  }

  /// 添加状态监听器
  void addStatusListener(String url, CacheStatusListener listener) {
    _checkMemoryPressure();

    _statusListeners.putIfAbsent(url, () => <CacheStatusListener>{});
    _statusListeners[url]!.add(listener);

    debugPrint('CacheMemoryManager: 添加状态监听器 - $url');
  }

  /// 移除状态监听器
  void removeStatusListener(String url, CacheStatusListener listener) {
    final listeners = _statusListeners[url];
    if (listeners != null) {
      listeners.remove(listener);
      if (listeners.isEmpty) {
        _statusListeners.remove(url);
      }
    }

    debugPrint('CacheMemoryManager: 移除状态监听器 - $url');
  }

  /// 添加错误监听器
  void addErrorListener(String url, CacheErrorListener listener) {
    _checkMemoryPressure();

    _errorListeners.putIfAbsent(url, () => <CacheErrorListener>{});
    _errorListeners[url]!.add(listener);

    debugPrint('CacheMemoryManager: 添加错误监听器 - $url');
  }

  /// 移除错误监听器
  void removeErrorListener(String url, CacheErrorListener listener) {
    final listeners = _errorListeners[url];
    if (listeners != null) {
      listeners.remove(listener);
      if (listeners.isEmpty) {
        _errorListeners.remove(url);
      }
    }

    debugPrint('CacheMemoryManager: 移除错误监听器 - $url');
  }

  /// 更新缓存状态（LRU管理）
  void updateCacheState(String url, String state) {
    // 移除旧记录（如果存在）
    _cacheStates.remove(url);

    // 添加新记录到末尾
    _cacheStates[url] = state;
    _stateTimestamps[url] = DateTime.now();

    // 检查是否超过最大缓存状态数
    while (_cacheStates.length > maxCacheStates) {
      final oldestUrl = _cacheStates.keys.first;
      _cacheStates.remove(oldestUrl);
      _stateTimestamps.remove(oldestUrl);
      debugPrint('CacheMemoryManager: 清理LRU缓存状态 - $oldestUrl');
    }
  }

  /// 获取缓存状态
  String? getCacheState(String url) {
    final state = _cacheStates[url];
    if (state != null) {
      // 更新访问时间（LRU）
      updateCacheState(url, state);
    }
    return state;
  }

  /// 清理指定URL的所有监听器
  void clearUrlListeners(String url) {
    _progressListeners.remove(url);
    _statusListeners.remove(url);
    _errorListeners.remove(url);
    _cacheStates.remove(url);
    _stateTimestamps.remove(url);

    debugPrint('CacheMemoryManager: 清理URL所有监听器 - $url');
  }

  /// 检查内存压力并清理
  void _checkMemoryPressure() {
    final totalListeners = _getTotalListenerCount();

    if (totalListeners > maxActiveListeners) {
      debugPrint('CacheMemoryManager: 检测到内存压力，开始清理 (当前监听器: $totalListeners)');
      _performCleanup(aggressive: true);
    }
  }

  /// 启动定期清理任务
  void _startCleanupTimer() {
    _cleanupTimer?.cancel();
    _cleanupTimer = Timer.periodic(cleanupInterval, (_) {
      _performCleanup(aggressive: false);
    });
  }

  /// 执行清理任务
  void _performCleanup({required bool aggressive}) {
    final now = DateTime.now();
    final urlsToClean = <String>[];

    // 查找过期状态
    _stateTimestamps.forEach((url, timestamp) {
      if (now.difference(timestamp) > staleStateTimeout) {
        urlsToClean.add(url);
      }
    });

    // 清理过期状态
    for (final url in urlsToClean) {
      _cacheStates.remove(url);
      _stateTimestamps.remove(url);
    }

    if (aggressive) {
      // 激进清理：移除空的监听器集合
      _progressListeners.removeWhere((_, listeners) => listeners.isEmpty);
      _statusListeners.removeWhere((_, listeners) => listeners.isEmpty);
      _errorListeners.removeWhere((_, listeners) => listeners.isEmpty);

      // 如果还是太多，清理最老的缓存状态
      while (_cacheStates.length > maxCacheStates ~/ 2) {
        final oldestUrl = _cacheStates.keys.first;
        _cacheStates.remove(oldestUrl);
        _stateTimestamps.remove(oldestUrl);
      }
    }

    if (urlsToClean.isNotEmpty || aggressive) {
      debugPrint(
          'CacheMemoryManager: 清理完成 - 清理${urlsToClean.length}个过期状态, 当前监听器: ${_getTotalListenerCount()}, 缓存状态: ${_cacheStates.length}');
    }
  }

  /// 获取总监听器数量
  int _getTotalListenerCount() {
    int count = 0;
    _progressListeners.values.forEach((listeners) => count += listeners.length);
    _statusListeners.values.forEach((listeners) => count += listeners.length);
    _errorListeners.values.forEach((listeners) => count += listeners.length);
    return count;
  }

  /// 获取内存使用统计
  Map<String, dynamic> getMemoryStats() {
    return {
      'totalListeners': _getTotalListenerCount(),
      'progressListeners': _progressListeners.length,
      'statusListeners': _statusListeners.length,
      'errorListeners': _errorListeners.length,
      'cacheStates': _cacheStates.length,
      'memoryPressure': _getTotalListenerCount() > maxActiveListeners,
    };
  }

  /// 获取内存报告（测试专用API）
  Map<String, dynamic> getMemoryReport() {
    return {
      'maxUrls': maxCacheStates,
      'maxMemoryUsage': maxActiveListeners * 1024, // 简单估算
      'activeUrls': _cacheStates.length,
      'memoryUsage': _getTotalListenerCount() * 256, // 简单估算每个监听器256字节
      'lruCacheSize': _cacheStates.length,
    };
  }

  /// 添加URL状态（测试专用API）
  void addUrlState(String url, String status) {
    updateCacheState(url, status);
  }

  /// 更新URL状态（测试专用API）
  void updateUrlState(String url, String status) {
    updateCacheState(url, status);
  }

  /// 手动清理（测试专用API）
  void cleanup() {
    _performCleanup(aggressive: true);

    // 额外清理：强制清理一半的缓存状态（用于测试）
    final statesToRemove = _cacheStates.length ~/ 2;
    final urlsToRemove = _cacheStates.keys.take(statesToRemove).toList();

    for (final url in urlsToRemove) {
      _cacheStates.remove(url);
      _stateTimestamps.remove(url);
    }

    debugPrint('CacheMemoryManager: 强制清理 ${urlsToRemove.length} 个缓存状态');
  }

  /// 释放所有资源
  void dispose() {
    if (!_isInitialized) return;

    _cleanupTimer?.cancel();
    _cleanupTimer = null;

    _progressListeners.clear();
    _statusListeners.clear();
    _errorListeners.clear();
    _cacheStates.clear();
    _stateTimestamps.clear();

    _isInitialized = false;
    debugPrint('CacheMemoryManager: 资源释放完成');
  }
}
